<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    
</body>
<script>

    // 3. 封装功能：parse(json)，返回值是一个对象
    //     - 原数据：'{"name":"admin","age":18}'
    //     - 现数据：{name:"admin",age:18}
    // 4. 封装功能：stringify(obj)，返回值是一个json
    //     - 原数据：{name:"admin",age:18}
    //     - 现数据：'{"name":"admin","age":18}'

    const json = '{"name":"admin","age":18,"abc":true,"qwe":null}';
    console.log( json );
    console.log( parse(json) );

    console.log("=======");

    const obj = {name:"admin",age:18,abc:true,qwe:null,fn:function(){},asd:undefined,zxc:NaN};
    console.log( obj );
    console.log( stringify(obj) );

    console.log("=======");

    function stringify(obj){
        let str = "";
        for(let i in obj){
            if(typeof obj[i] !== "function" && typeof obj[i] !== "undefined"){
                str += `"${i}":${ typeof obj[i]==="string" ? `"${obj[i]}"` : (isNaN(obj[i]) ? 'null' : obj[i]) },`;
            }
        }
        return `{${str.slice(0,-1)}}`;
    }

    function parse(json){
        const o = {};
        json.slice(1, -1).split(",").forEach(val=>{
            const arr = val.split(":");

            // o[arr[0].slice(1, -1)] = arr[1].includes('"') ? arr[1].slice(1,-1) : (arr[1][0]!=="t" && arr[1][0]!=="f" && arr[1][0]!=="n" ? Number(arr[1]) : (arr[1][0] === "n" ? null : Boolean(arr[1])));

            let value = null;
            if(arr[1].includes('"')){
                value = arr[1].slice(1,-1)
            }else if(arr[1][0] === "n"){
                value = null;
            }else if(arr[1][0]==="t" || arr[1][0]==="f"){
                value = Boolean(arr[1])
            }else{
                value = Number(arr[1])
            }

            o[arr[0].slice(1, -1)] = value;
        })

        return o;
    }





    
</script>
</html>